package com.zs.grain.ui

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.widget.SeekBar
import android.widget.Toast
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.mvvm.BaseMvvmDialog
import com.zs.grain.R
import com.zs.grain.databinding.DialogAdjustBinding


class AdjustDialog : BaseMvvmDialog<DialogAdjustBinding, AdjustViewModel>(),
    SeekBar.OnSeekBarChangeListener, TextWatcher {

    override val layoutId = R.layout.dialog_adjust

    override fun initViewModel(binding: DialogAdjustBinding) {
        binding.vm = this.mViewModel
        binding.view = this

        binding.seekBar.setOnSeekBarChangeListener(this)
        binding.etValue.addTextChangedListener(this)
        LiveEventBus.get("KeyEvent", Boolean::class.java).observe(this, Observer{
            mViewModel.onClickConfirm()
        })
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        if (fromUser) {
            mViewModel.value.value = (progress + (mViewModel.imin.value ?: 0)).toDouble()
        }
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
    }

    override fun afterTextChanged(s: Editable?) {
        //var a = 20
        if(!s.toString().contains(".")){

            //print(s.toString().length)
            //s.toString().subSequence(0,s.toString().length)
        }
        //mViewModel.value.value = s.toString().toDouble()
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        //mBinding.etValue.setSelection(s.toString().length)
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s?.length ?: 0 > 0) {
            //if(s.toString().contains(".")) {
                //s = s.toString().subSequence(0,s.toString().length-1)
                //}
                //mViewModel.value.value = s.toString().toDouble()
                mBinding.etValue.setSelection(s.toString().length)
//                mViewModel.value.value = s.toString().subSequence(0,s.toString().length-1).toString().toDouble()
//                mBinding.etValue.setSelection(s.toString().subSequence(0,s.toString().length-1).length)
            //}
        } else {
            //mViewModel.value.value = null
        }
    }

    internal lateinit var mHandler: Handler
    var value: Double? = null
        private set

    override fun initArguments() {
        var args = arguments!!
        var title = args.getString("Title")
        var min = args.getDouble("Min")
        var max = args.getDouble("Max")
        var value = args.getDouble("Value")
        var unitType = if(args.getString("UnitType") =="no_unit") "" else args.getString("UnitType")
        mViewModel.init(title, min, max, value,unitType)
    }

    override fun initView() {
        this.isCancelable = false
    }

    override fun onUiNotify(name: String, bundle: Bundle) {
        super.onUiNotify(name, bundle)
        when (name) {
            "Confirm" -> {
                //
//
                mViewModel.value.value = mBinding.etValue.text.toString().toDouble()
                if((mViewModel.min.value!! <= (mViewModel.value.value!!))&&(mViewModel.value.value!! <= mViewModel.max.value!!)){
                    this.value = Math.max(mViewModel.value.value ?: 0.0, mViewModel.min.value ?: 0.0)//.toInt()
                    this.value = Math.min(this.value ?: 0.0, mViewModel.max.value ?: 0.0)
                    mHandler.sendEmptyMessage(0);
                }else{
                    Toast.makeText(context,"超出范围,请重新输入",Toast.LENGTH_SHORT)
                }
            }
            "Cancel" -> mHandler.sendEmptyMessage(0);
        }
    }

    fun showDialog(manager: FragmentManager, tag: String): Double? {
        mHandler = object : Handler() {
            override fun handleMessage(mesg: Message) {
                throw RuntimeException()
            }
        }
        super.show(manager, tag)
        try {
            Looper.getMainLooper()
            Looper.loop()
        } catch (e: Exception) {
            var a = 20
        }
        this.dismiss()
        return this.value
    }

    companion object {
        val TAG = "AdjustDialog"
        fun newInstance(title: String, min: Double, max: Double, value: Double, unitType: String): AdjustDialog {
            val dlg = AdjustDialog()
            var args = Bundle();
            args.putString("Title", title)
            args.putDouble("Min", min)
            args.putDouble("Max", max)
            args.putDouble("Value", value)
            args.putString("UnitType", unitType)
            dlg.arguments = args
            return dlg
        }
    }
}
